package _01_sort;

import org.junit.Test;

import java.util.Arrays;

/**
 * @author: mornd
 * @dateTime: 2023/5/20 - 21:23
 * 冒泡排序
 * 其基本思想是通过相邻元素之间的比较和交换，使得较大的元素逐渐向右侧移动到正确的位置
 */
public class BubbleSort {
    @Test
    public void test() {
        int[] arr = {22, 6, 8, 16, 28, 4, 7, 67, 68};
//        int[] arr = {1,2,3,4,5,6};
        System.out.println("before:" + Arrays.toString(arr));
        bubbleSort_V2(arr);
        System.out.println("after:" + Arrays.toString(arr));
    }

    private void bubbleSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            System.out.println("i=" + i);
            boolean swapped = false;
            for (int j = 0; j < arr.length - 1 - i; j++) {
                System.out.println("j=" + j);
                if (arr[j] > arr[j + 1]) {
                    swapped = true;
                    int t = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = t;
                }
            }
            if (!swapped) {
                break;
            }
        }
    }

    private void bubbleSort_V2(int[] arr) {
        int i = arr.length - 1;
        for (; ; ) {
            System.out.println("外层..." + Arrays.toString(arr));
            int last = 0;
            for (int j = 0; j < i; j++) {
                System.out.println("内层 j=" + j);
                if (arr[j] > arr[j + 1]) {
                    last = j;
                    int t = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = t;
                }
            }
            i = last;
            if (last == 0) {
                break;
            }
        }
    }
}
